package com.oocl.crm.cmdparseipml;

import javax.swing.text.html.parser.Entity;

import com.oocl.cmdparse.CmdParser;
import com.oocl.crm.repository.impl.CustomerDataProcessImpl;
import com.oocl.rcm.db.MyLinkListFactory;
import com.oocl.rcm.db.MyLinkedList;
import com.oocl.rcm.entry.Entry;
import com.oocl.rcm.model.Customer;
import com.oocl.rcm.util.FormatPrinter;

public class CmdParserIpml implements CmdParser{
	
	private static CustomerDataProcessImpl cspi;
	private static MyLinkedList<Customer>  db; 
	private static int index;
	private static FormatPrinter fp;
	
	public CmdParserIpml(){
		db = MyLinkListFactory.getInstance();
		index = 11;
		cspi = new CustomerDataProcessImpl();
		fp = new FormatPrinter();
	}

	public void processAdd(String cmd) {
		Customer c = cmdToCustomer(cmd);
		c.setId(index);
		cspi.addCustomer(db, c);
		this.index++;
		fp.printAddSuccess();
	}

	public void processUpdate(String cmd) {
		Customer c = cmdToCustomer(cmd);
		cspi.updateCustomer(db, c);
		fp.printUpdateSuccess();	
	}

	public void processDelete(String cmd) {
		Customer c = cmdToCustomer(cmd);
		int id = c.getId();
		cspi.deleteCustomer(db, id);
		fp.printDeleteSuccess();
	}

	public Customer[] processSort(String cmd) {
		Customer[] cs = cspi.sort(db);
		return cs;
	}

	public Customer[] find(String cmd) {
		if(cmd.split(" ").length == 1){
			Customer[] cs = new Customer[db.getLen()];
			for (int i = 0; i < db.getLen(); i++) {
				cs[i] = db.get(i).getData();
			}
			return cs;
		}else{
			Customer[] cs = cspi.find(db, cmd.split(" ")[1]);
			return cs;
		}
		
	}

	public int getIndex() {
		return index;
	}
	
	public Customer cmdToCustomer(String cmd){
		Customer c = new Customer();
		String infos = cmd.split(" ")[1];
		String[] info = infos.split(",");
		for (int i = 0; i < info.length; i++) {
			String key = info[i].split(":")[0];
			String value = info[i].split(":")[1];
			if("id".equals(key)){
				c.setId(Integer.valueOf(value));
			}
			if("name".equals(key)){
				c.setName(value);
			}
			if("sex".equals(key)){
				c.setSex(value);
			}
			if("address".equals(key)){
				c.setAddress(value);
			}
			if("call".equals(key)){
				c.setCall(value);
			}
			if("birthday".equals(key)){
				c.setBirthday(value);
			}
		}
		return c;
	}
}
